#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# copyright (c) 2010 by The Codedrawer Team
#
# 成员
# xkhhdx(HD.Huo)	viking9345(C.Cai)	renxing225(X.Ren)
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#		 http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# 代码来自：http://code.google.com/p/codedrawer/
#
#--- 更新记录 ---
#成员		时间			简述
#xkhhdx		0:51 2010-8-30	更换新的 UI
#xkhhdx		20:30 2010-8-29	添加了对行号的支持
#xkhhdx		1:30 2010-8-21	支持了 AJAX
#xkhhdx		1:29 2010-8-21	添加了类 raw_output 以支持ajax
#xkhhdx		23:53 2010-8-21	显示原始代码的时候 可以显示出原始的 HTML 来
#xkhhdx		16:14 2010-7-21	把 HTML 页面移出 使用了模板
#xkhhdx		16:28 2010-6-25 GAE 平台入口
#
#--- 计划列表 ---
#提出者		时间			是否解决	解决者	计划简述		解决简述
#
import os
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

from core import *
#from core.core import *
from core.cpp_code_render import *
from core.python_code_render import *
from core.java_code_render import *
from core.php_code_render import *

#code_renderers_list = ["cpp", "python", "java", "php", ]

code_lang_name = {
	"cpp"		:	"C++",
	"python"	:	"Python",
	"java"		:	"Java",
	"php"		:	"PHP",
	}

code_renderers_list = code_lang_name.keys()

class MainHandler(webapp.RequestHandler):
    def get(self):
        code_renderers=""
        
        for lang in code_renderers_list:
            code_renderers += "<option value='%s'> %s </option>" %( lang, code_lang_name[lang] )

        template_values = {
            'code_renderers'	:	code_renderers,
            }
            
        path = os.path.join(os.path.dirname(__file__), 'static')
        path = os.path.join(path, 'mainpage.html')
        #logging.info("path="+path)
        self.response.out.write(template.render(path, template_values))

        #for x in os.environ:
        #	self.response.out.write("%20s : %s <br/>" % (x,os.environ[x]))

class display_output(webapp.RequestHandler):
    def get(self):
        self.redirect("/")

    def post(self):
    	show_line_number = self.request.get('showlinenumber') == 'true'
    	logging.info("show_line_number = "+`show_line_number`)
    	
        plain_code = self.request.get('plain_code')
        code_lang = self.request.get('code_lang')
        
        if not code_lang in code_renderers_list or len(code_lang)==0:
            self.response.out.write( "请选择语言<br>" )
            self.response.out.write( "&nbsp;<a href='javascript: history.go(-1);'>返回</a>" )
            return
        
        # 开始渲染
        cr = eval(code_lang + "_code_render('html')")
        cr.code_buffer = plain_code
        #logging.info(' plain_code='+plain_code)
        cr.linenumber(show_line_number)
        cr.render()
        #logging.info(' cr.rendered_code_buffer='+cr.rendered_code_buffer)

        code_renderers=""
        for lang in code_renderers_list:
            if lang == code_lang:
                code_renderers += "<option value='%s' selected='selected'> %s </option>" %( lang, code_lang_name[lang] )
            else:
                code_renderers += "<option value='%s'> %s </option>" %( lang, code_lang_name[lang] )

        template_values = {
            'plain_code'			:	plain_code,
            'rendered_code'			:	cr.rendered_code_buffer,
            'rendered_html_code'	:	cr.prerender_escape_sequence_func(cr.rendered_code_buffer, True),
            'code_renderers'		:	code_renderers,
            }

        path = os.path.join(os.path.dirname(__file__), 'static')
        path = os.path.join(path, 'mainpage.html')
        #logging.info("path="+path)
        self.response.out.write(template.render(path, template_values))

        #self.response.out.write( "=========================<br>")

        #for x in os.environ:
        #	self.response.out.write("%20s : %s <br/>" % (x,os.environ[x]))

class raw_output(webapp.RequestHandler):
    def get(self):
        self.redirect("/")
        
    def post(self):
    	show_line_number = self.request.get('showlinenumber') == 'true'
        plain_code = self.request.get('plain_code')
        code_lang = self.request.get('code_lang')
        
        if not code_lang in code_renderers_list or len(code_lang)==0:
            # 以后这里改为返回 HTTP 错误
            self.response.out.write( "<!-- please select lang -->请选择语言<br>" )
            self.response.out.write( "&nbsp;<a href='/'>返回</a>" )
            return
        
        # 开始渲染
        cr = eval(code_lang + "_code_render('html')")
        cr.code_buffer = plain_code
        cr.linenumber(show_line_number)
        cr.render()
        
        self.response.out.write( cr.rendered_code_buffer )

def main():
    application = webapp.WSGIApplication(    [
                                            ('/', MainHandler),
                                            ('/mark', display_output),
                                            ('/getcodehtml', raw_output),
                                            ],
                                                debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()

